package mspbots.cw.client.core.app;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.client.core.AbstractToolsUtil;
import mspbots.cw.client.core.data.BaseSyncService;
import mspbots.cw.client.core.data.callbacks.CallbacksServiceImpl;
import mspbots.cw.client.core.client.ClientProperties;
import mspbots.cw.common.QueryParams;
import mspbots.cw.common.RedisKeys;
import mspbots.cw.common.ResultSync;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;

/**
 * com.mspbots.sync.scheduled.connectwise.ConnectWiseSyncService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/30
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class CwServiceImpl extends AbstractToolsUtil {

    private final Map<String, BaseSyncService> syncServiceMap;
    private final CallbacksServiceImpl callbacksService;

    public Mono<Boolean> onOff(Long tenantId, String onOff) {
        if ("ON".equalsIgnoreCase(onOff)) {
            return this.stringRedisTemplate.opsForValue()
                    .set(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + tenantId, onOff.toUpperCase(),
                            Duration.ofDays(3650));
        } else {
            return this.stringRedisTemplate.opsForValue()
                    .delete(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + tenantId);
        }
    }

    public Mono<JsonNode> initialize(Long tenantId, ClientProperties properties) {
        ResultSync resultSync = ResultSync.withDefault("TEST-SECURITY");
        return super.cwWebClient.get("/system/mySecurity", QueryParams.withDefault()
                .setFields("id,inquireLevel,moduleName,moduleDescription,moduleFunctionName"))
                .contextWrite(ctx -> ctx.put("properties", properties))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(result -> this.reactiveRedisTemplate.opsForValue()
                        .set(RedisKeys.TENANT_PROPERTIES_REDIS_KEY_PREFIX + tenantId, properties,
                                Duration.ofDays(36500)).subscribe(res -> log.info("save configuration is success")))
                .doOnNext(result -> this.callbacksService.initialize(properties).subscribe())
                .doOnSuccess(result -> Flux.fromStream(this.syncServiceMap.values().parallelStream())
                        .flatMap(v -> Flux.concatDelayError(
                                v.syncFast(properties),
                                v.syncSlow(properties),
                                v.syncSlower(properties))
                        ).subscribe());
    }

    public Mono<Void> delete(Long tenantId) {
        return this.loadProperties(tenantId)
                .flatMapMany(this.callbacksService::delAll)
                .doOnTerminate(() -> this.reactiveRedisTemplate.opsForValue()
                        .delete(RedisKeys.TENANT_PROPERTIES_REDIS_KEY_PREFIX + tenantId).subscribe())
                .then();
    }

    public Mono<ObjectNode> synchronise(Long tenantId, SyncRequest syncRequest) {
        return Mono.just(this.objectMapper.createObjectNode().put("result", "success"))
                .doOnNext(res -> this.loadProperties(tenantId)
                        .flatMapMany(properties -> Flux.fromStream(this.syncServiceMap.values().parallelStream())
                                .flatMap(v -> v.manualSync(properties, syncRequest)))
                        .delayElements(Duration.ofSeconds(100))
                        .subscribe(result -> log.info("Synchronise manual sync success."),
                                err -> log.error("Synchronise manual sync error, msg: {}", err.getMessage())));
    }

    public Mono<ResponseEntity<JsonNode>> requestApi(Long tenantId, String href) {
        return this.loadProperties(tenantId)
                .flatMap(property -> super.cwWebClient
                        .requestEntity(property,UriComponentsBuilder.fromHttpUrl(href).build().toUri())
                        .contextWrite(ctx -> ctx.put("properties", property)));
    }
}
